﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LEET.LEETCommon.AutomationAbstractions;
using LEET.CommonInterfaces.Automation;
using LEET.LEETCommon.Model;
using System.Windows.Automation;

namespace ExpandCollapse
{
    public class ExpandCollapseEventListener : AutomationElementEventListenerBase
    {

        AutomationPropertyChangedEventHandler handler;
        private IRegistryAccessor registry;

        public ExpandCollapseEventListener(IObservableWidget target, IRegistryAccessor reg)
        {
            this.RootTarget = target;
            this.registry = reg;
            Listening = false;
            try
            {
                handler = new AutomationPropertyChangedEventHandler(CatchEvent);
                registry.RegisterEventHandler(ExpandCollapsePattern.ExpandCollapseStateProperty, RootTarget.ae, handler);
                Listening = true;
            }
            catch (ArgumentException) { }
        }

        public override void Listen(IObservableWidget widget, String property, String newValue)
        {
            //In case element disappeared before it could be processed
            if (widget == null) return;

            string element = widget.GetUIAHierarchy(RootTarget).ToString();
            string state;
            if (newValue == "1")
                state = ExpandCollapseState.Expanded.ToString();
            else
                state = ExpandCollapseState.Collapsed.ToString();

            Delagate(new Event_Pair("ACTION\t| EXPNDCOLPS | " + element + " | " + state));

        }

        public override void Dispose()
        {
            registry.RemoveEventHandler(ExpandCollapsePattern.ExpandCollapseStateProperty, RootTarget.ae, handler);
            base.Dispose();
        }

    }

}
